<template>
	<div class="main-container">
		<!-- 顶部导航栏 -->
		<header class="top-header">
			<div class="logo-section">
				<span class="logo">⚡</span>
				<span class="system-name">客户需求响应</span>
			</div>
			<div class="user-section">
				<div class="user-info">
					<span class="user-name">{{ currentUserRealName || '用户' }}</span>
				</div>
			</div>
		</header>

		<!-- 主要内容区域 -->
		<div class="content-wrapper">
			<!-- 左侧菜单 -->
			<aside class="sidebar">
				<el-menu :default-active="activeMenu" class="el-menu-vertical" router>
					<el-menu-item index="/main">
						<el-icon>
							<HomeFilled />
						</el-icon>
						<span>首页</span>
					</el-menu-item>
					<!-- TODO：模板渲染目录 -->
					<el-menu-item index="/customer">
						<el-icon>
							<User />
						</el-icon>
						<span>客户管理</span>
					</el-menu-item>
					<el-menu-item index="/powerZone">
						<el-icon>
							<Location />
						</el-icon>
						<span>区域管理</span>
					</el-menu-item>
					<el-menu-item index="/user">
						<el-icon>
							<UserFilled />
						</el-icon>
						<span>用户管理</span>
					</el-menu-item>
					<el-menu-item index="/powerEquipment">
						<el-icon>
							<Tools />
						</el-icon>
						<span>设备管理</span>
					</el-menu-item>
					<el-menu-item index="/customerDemand">
						<el-icon>
							<Operation />
						</el-icon>
						<span>客户需求管理</span>
					</el-menu-item>
					
					<!-- 仅订阅用户可见的分析路由 -->
				<template v-if="companyInfo?.hasSubscription === 1 || hasSubscription === 1">
					
					<el-menu-item index="/customerAnalysis">
						<el-icon>
							<PieChart />
						</el-icon>
						<span>客户与需求分析</span>
					</el-menu-item>
					<el-menu-item index="/equipmentAnalysis">
						<el-icon>
							<TrendCharts />
						</el-icon>
						<span>设备与容量分析</span>
					</el-menu-item>
					<el-menu-item index="/prioritySupport">
						<el-icon>
							<Star />
						</el-icon>
						<span>优先支持</span>
					</el-menu-item>
				</template>
					
					<el-menu-item divided @click="logout">
						<el-icon>
							<SwitchButton />
						</el-icon>
						<span>退出系统</span>
					</el-menu-item>
				</el-menu>
			</aside>

			<!-- 右侧内容 -->
			<main class="main-content">
				<router-view />
			</main>
		</div>

		<!-- 底部信息 -->
		<footer class="footer">
			<p>客户需求响应 &copy; {{ new Date().getFullYear() }} All Rights Reserved.</p>
		</footer>
	</div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, provide } from "vue";
import { useRouter } from "vue-router";
import {
	HomeFilled,
	User,
	UserFilled,
	Location,
	Tools,
	Operation,
	PieChart,
	TrendCharts,
	Star,
	SwitchButton,
} from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus';
import { getCompanyInfo } from '../apis/companyAPI';

// 初始化路由
const router = useRouter();

// 获取当前用户真实姓名
const currentUserRealName = computed(() => {
	try {
		const userInfo = localStorage.getItem('userInfo');
		if (userInfo) {
			const parsed = JSON.parse(userInfo);
			return parsed.realName || parsed.username || '用户';
		}
	} catch (error) {
		console.error('解析用户信息失败:', error);
	}
	return '用户';
});

// 企业信息状态
const companyInfo = ref(null);
const isLoading = ref(false);
const hasSubscription = ref(0); // 用于安全访问localStorage中的订阅状态

// 计算当前激活的菜单
const activeMenu = computed(() => {
	return router.currentRoute.value.path;
});

// 获取企业信息
const fetchCompanyInfo = async () => {
	isLoading.value = true;
	try {
		const response = await getCompanyInfo();
		companyInfo.value = response.data;
		// 保存订阅状态到本地存储
		const subscriptionValue = response.data.hasSubscription || 0;
		localStorage.setItem('hasSubscription', subscriptionValue);
		hasSubscription.value = subscriptionValue;
	} catch (error) {
		console.error('获取企业信息失败:', error);
		ElMessage.error('获取企业信息失败');
		// 出错时尝试从localStorage读取
		safeLoadSubscriptionStatus();
	} finally {
		isLoading.value = false;
	}
};

// 安全地从localStorage加载订阅状态
const safeLoadSubscriptionStatus = () => {
	try {
		if (typeof localStorage !== 'undefined') {
			hasSubscription.value = parseInt(localStorage.getItem('hasSubscription') || '0');
		}
	} catch (error) {
		console.error('读取localStorage失败:', error);
		hasSubscription.value = 0;
	}
};

// 退出登录方法
const logout = () => {
	try {
		if (typeof localStorage !== 'undefined') {
			localStorage.removeItem("token");
			localStorage.removeItem("hasSubscription");
			localStorage.removeItem("userInfo");
			hasSubscription.value = 0;
		}
	} catch (error) {
		console.error('清理localStorage失败:', error);
	}
	router.push("/login");
};

// 刷新页面方法，用于订阅状态变化后重新渲染路由
const refreshPage = () => {
	// 先重新获取企业信息，确保最新的订阅状态
	fetchCompanyInfo().then(() => {
		// 强制刷新当前路由
		router.replace(router.currentRoute.value.fullPath);
	});
};

// 提供给子组件的刷新方法
provide('refreshPage', refreshPage);

// 全局事件总线，方便其他组件调用刷新方法
// 确保不重复注册，避免内存泄漏
if (!window.refreshSubscriptionPage) {
  window.refreshSubscriptionPage = refreshPage;
}

// 获取用户信息
const getUserInfo = async () => {
	try {
		const { getCurrentUser } = await import('../apis/userAPI.js');
		const response = await getCurrentUser();
		if (response.code === 200 && response.data) {
			localStorage.setItem('userInfo', JSON.stringify(response.data));
		}
	} catch (error) {
		console.error('获取用户信息失败:', error);
	}
};

// 组件挂载时获取企业信息和用户信息
onMounted(() => {
	// 先安全加载订阅状态
	safeLoadSubscriptionStatus();
	// 然后获取企业信息
	fetchCompanyInfo();
	// 获取用户信息
	getUserInfo();
});

// 组件卸载时清理全局事件
onUnmounted(() => {
	if (window.refreshSubscriptionPage) {
		delete window.refreshSubscriptionPage;
	}
});
</script>
<style scoped>
.main-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	overflow: hidden;
}

/* 顶部导航栏 */
.top-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 60px;
	padding: 0 20px;
	background-color: #ffffff;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	z-index: 1000;
}

/* 顶部导航栏样式已优化 */
.logo-section {
	display: flex;
	align-items: center;
	gap: 10px;
}

.logo {
	font-size: 24px;
}

.system-name {
	font-size: 18px;
	font-weight: bold;
	color: #1890ff;
}

/* 顶部导航栏已简化 */

.user-section {
	display: flex;
	align-items: center;
}

.user-info {
	display: flex;
	align-items: center;
	gap: 5px;
	cursor: pointer;
	padding: 8px 12px;
	border-radius: 4px;
	transition: background-color 0.3s;
}

.user-info:hover {
	background-color: #f5f5f5;
}

/* 内容区域 */
.content-wrapper {
	display: flex;
	flex: 1;
	overflow: hidden;
}

/* 左侧菜单 */
.sidebar {
	width: 200px;
	background-color: #ffffff;
	border-right: 1px solid #e0e0e0;
	overflow-y: auto;
}

/* 主内容区 */
.main-content {
	flex: 1;
	padding: 20px;
	overflow-y: auto;
	background-color: #f5f7fa;
}

/* 底部信息 */
.footer {
	height: 40px;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #ffffff;
	border-top: 1px solid #e0e0e0;
	color: #909399;
	font-size: 12px;
}
</style>
